<template>
  <div>
    <div class="searchBox">
        <div class="inputItem">
            <div class="label">部门：</div>
            <div class="val">
              <JSelectDept v-model:value="deptId"  @change="handleChangeDeptId" :multiple="false"></JSelectDept>
            </div>
        </div>
        <div class="inputItem">
          <div class="label">分组：</div>
          <div class="val"> 
              <!-- <a-input v-model="groupId"></a-input> -->
               <a-select style="width:220px;"  v-model:value="groupId" :options="groupOption" />
              <!-- <JSelectInput style="width:220px;"
              v-model:value="groupId"
              :options="groupOption"
              @change="groupChange"
            ></JSelectInput> -->
          </div>
        </div>
        <div class="inputItem">
             <div class="label">工号：</div>
            <div class="val">
              <a-input v-model:value="personCode"></a-input>
            </div>
        </div>
        <div class="inputItem">
            <div class="label">姓名：</div>
            <div class="val">
              <a-input v-model:value="personName"></a-input>
            </div>
        </div>

        <div class="inputItem">
           <div class="label">时间：</div>
           <a-range-picker style="height:32px;" v-model:value="rangeTime" @change="rangeTimeChange" valueFormat="YYYY-MM-DD" />
        </div>
         <a-button type="primary" style="margin-left:15px;" @click="handleSearch" preIcon="ant-design:search-outlined"> 查询</a-button>
         <a-button style="margin-left:15px;" @click="handleRest" preIcon="ic:baseline-restart-alt"> 重置</a-button>
    </div>
    <div class="tableBox">
      <BasicTable
        ref="tableRef"
        :columns="listColumns"
        :dataSource="dataSource"
        :border="true"
        :pagination="paginationProp"
      >
        <!-- <template #rowItem="{ record,text }"> -->
        <template #rowItem="{ record,text }">
          <!-- <Tag color="green"> -->
            <!-- {{record}} -->
             <div v-if="!text.length">
              <div>
                休
              </div>
            </div>
            <div v-for="(item,index) in text" :key="index">
              <div>
                {{item.periodName}}
              </div>
              <div v-if="selectWorkId && selectWorkId==(item.id+item.workDate)" style="margin-bottom: 5px;">
                <a-select
                    @change="workGroupChange"
                    style="width: 130px;" :fieldNames="{label:'name',value:'id' }"
                    :options="workGroupOptions"
                >
                </a-select>
              </div>
              <div>
                <Tag  v-if="item.periodName!='-'" color="blue" style="cursor: pointer;margin-right:5px;"  @click="handleChangeDateWork(item.id,item)">调</Tag>
                <Tag  v-if="item.periodName!='-'" color="green" style="cursor: pointer;margin-right:5px;"  @click="handleChangeRowItem(item,record)">换</Tag>
                <Tag v-if="item.periodName!='-'" color="red"  style="cursor: pointer;" @click="handleDelRowItem(item.id,)">删</Tag>
              </div>
            </div>
           
          <!-- </Tag> -->
        </template>
        <template #tableTitle>
          <a-button  type="primary" preIcon="ant-design:plus-outlined" @click="handleScheduleDialog"> 排班</a-button>
          <!-- <a-button  type="primary" preIcon="ant-design:plus-outlined" @click="handleChange"> 换班</a-button> -->
        </template>
      </BasicTable>
    </div>
    
    <AttScheduleInitModel @register="registerInitModal" @success="handleSuccess"></AttScheduleInitModel>
    <AttScheduleChange @register="registerModal" @success="handleSuccess"></AttScheduleChange>

  </div>
</template>

<script lang="ts" name="attendance-attSchedule" setup>
  import {ref, reactive, computed, unref,toRefs,onMounted} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import {useModal} from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import AttScheduleChange from './components/AttScheduleChange.vue'
  import AttScheduleInitModel from './components/AttScheduleInitModel.vue'
  import { Tag, } from 'ant-design-vue';
  import {columns, superQuerySchema} from './AttSchedule.data';
  import {autoSchedule,personSchedulelist,GroupList, deleteOne, batchDelete, getImportUrl,getExportUrl,attTimePeriodList,changeTimePeriod} from './AttSchedule.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import {onMountedOrActivated} from "@/hooks/core/onMountedOrActivated";
  import JSelectInput from '/@/components/Form/src/jeecg/components/JSelectInput.vue';
  import JSelectDept from '/@/components/Form/src/jeecg/components/JSelectDept.vue';

  import { deleteOne as deleteOneDate} from '@/views/attendance/schedule/AttSchedule.api';

  


  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  //注册model
  const [registerModal, {openModal}] = useModal();
  const [registerInitModal, {openModal:initModal}] = useModal();
  

  const data = defineProps({
    workDate:String,
    departmentId:String,
    rload:Object,
  })
  const total = ref(0);
  let pageNo = ref(1)
  let pageSize = ref(10)
  
  const paginationProp = ref({
    showSizeChanger: false,
    showQuickJumper: true,
    pageSize,
    current: pageNo,
    total,
    showTotal: (total) => `总 ${total} 条`,
    onChange: pageChange,
    onShowSizeChange: pageSizeChange,
  });
  function pageChange(p, pz) {
    pageNo.value = p;
    pageSize.value = pz;
    getList();
  }
  function pageSizeChange(current, size) {
    pageSize.value = size;
    getList();
  }
  const dataSource = ref([])
  let rangeTime = ref([])
  let sdate = ref('')
  let edate = ref('')
  let deptId = ref('')
  let personCode = ref('')
  let personName = ref('')
  let groupId = ref('')
  let workGroupOptions = ref([])
  let selectWorkId = ref('')
  let workDateId = ref('')

  const listColumns =  ref([
    {
      title: '部门',
      dataIndex: 'deptName',
    },
    {
      title: '姓名',
      dataIndex: 'personName',
    },
    {
      title: '工号',
      dataIndex: 'personCode',
    },
  ])

  function groupChange(e){
    // console.log(e);
    // getGroupList(e)
  }

  const groupOption = ref([
    // { label: '男', value: '1' },
    // { label: '女', value: '2' },
  ]);

  function workGroupChange(e){
   
    changeTimePeriod({
      timePeriodId: e,
      id: workDateId.value
    }).then(res=>{
      selectWorkId.value = ''
      getList()
    })

  }

  function handleChangeDateWork(id,item){
    // let id = column.dataIndex+'-id'
    selectWorkId.value = id + item.workDate
    // console.log(selectWorkId.value);
    workDateId.value = id
    workGroupOptions.value = []
    attTimePeriodList({
      attScheduleId: id
    }).then(res=>{
      res.records.forEach(item=>{
        item.workTime = item.workTime.substring(0,5)
        item.leaveTime = item.leaveTime.substring(0,5)
        item.name = item.name+' '+item.workTime+'-'+item.leaveTime
      })
      workGroupOptions.value = res.records
    })
  }

  function handleChangeRowItem(item,record){
    let obj = {
      originaDate : item.workDate,
      originalName : record.personName,
      timePeriodName1 : item.periodName+' '+item.workTime+'至'+item.leaveTime,
      originalId : item.id,
    }
    console.log(obj);
     openModal(true, {
       record:obj,
       isUpdate: true,
       showFooter: true,
     });
  }

  function handleDelRowItem(id){
    deleteOneDate({id}, getList)
  }

  function handleChange(record: Recordable) {
     openModal(true, {
      //  record,
       isUpdate: true,
       showFooter: true,
     });
   }

  function handleChangeDeptId(e){
    if(e[0]){
      deptId.value = e[0]
    }else{
      deptId.value = ''
    }
    getGroupList()
  }

  function handleSearch(){
    getList()
  }
  function handleRest(){
    rangeTime.value = []
    sdate.value = ''
    edate.value = ''
    deptId.value = ''
    personCode.value = ''
    personName.value = ''
    groupId.value = ''
    pageNo.value = 1
    pageSize.value = 10
    getList()
  }

  function rangeTimeChange(e){
    console.log(e);
    sdate.value = e[0]
    edate.value = e[1]
  }

  function getGroupList(e){
    GroupList({
      name:e ? e : '',
      departmentId: deptId.value ? deptId.value: '',
      pageSize: 1000,
    }).then(res=>{
      groupOption.value = []
      res.records.forEach(item=>{
        groupOption.value.push({
          label: item.name,
          value: item.id
        })
      })

    })
  }

  function getList(){
     let data ={
      sdate : sdate.value,
      edate : edate.value,
      deptId : deptId.value,
      personCode : personCode.value,
      personName : personName.value,
      groupId : groupId.value,
      pageNo : pageNo.value,
      pageSize : pageSize.value,
    }
    personSchedulelist(data).then(res=>{
      listColumns.value = listColumns.value.slice(0,3)
      if(res.records.length){
           let tempObj = res.records[0]
          let keys =  Object.keys(tempObj) 
          let dateKeys = []
          keys.forEach(item=>{
            if(isDate(item)){
              dateKeys.push(item)
            }
          })
          dateKeys.sort((a, b) => {
            return Date.parse(a) - Date.parse(b);
          });
          dateKeys.forEach(item=>{
            let obj =  {
                title: item,
                dataIndex: item,
                slots: { customRender: 'rowItem' }
              }
              listColumns.value.splice(listColumns.value.length,0,obj)
          })
      }
        dataSource.value = res.records
      total.value = res.total
    })
  }

  onMountedOrActivated(()=>{
  })

  onMounted(()=>{
    getList()
    getGroupList()
  })

function isDate(value) {
   return !isNaN(Date.parse(value));
}
   /**
    * 新增事件
    */
  function handleAdd() {
     openModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
  const setworkdate = (w)=>{
    alert(w);
  }
  async function handleSchedule(){
    openModalSche(true, {
     setworkdate
    });
   //
  }
  async function handleHandSchedule(){
    openModalHandSchedule(true, {
      setworkdate
    });
    //
  }

  function handleScheduleDialog(record: Recordable) {
     initModal(true, {
      //  record,
       sdate : sdate.value,
       edate : edate.value,
       deptId : deptId.value,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      handleSearch()
      // (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      */
  function getTableAction(record){
       return [
         {
           label: '编辑',
           onClick: handleEdit.bind(null, record),
         }
       ]
   }
     /**
        * 下拉操作栏
        */
  function getDropDownAction(record){
       return [
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         }, {
           label: '删除',
           popConfirm: {
             title: '是否确认删除',
             confirm: handleDelete.bind(null, record),
             placement: 'topLeft',
           }
         }
       ]
   }


</script>

<style lang="less" scoped>
.searchBox{
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  background: #fff;
  margin: 10px;
  padding-bottom: 12px;
  min-height: 60px;
  .inputItem{
    padding: 12px;
    width: 25%;
    display: flex;
  }
  .label{
    display: inline-flex;
    justify-content: flex-end;
    align-items: center;
    width: 130px;
    height: 32px;
    color: rgba(0, 0, 0, 0.88);
  }
  .val{
    width: 220px;
  }
}

.tableBox{
  background: #fff;
  padding: 6px;
  margin: 10px;
}
</style>
